package com.gmss.crawler.module.patent.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gmss.crawler.constants.Base;
import com.gmss.crawler.constants.Constants;
import com.gmss.crawler.enums.AcademicianEnum;
import com.gmss.crawler.enums.CommonEnum;
import com.gmss.crawler.module.patent.domain.Patent;
import com.gmss.crawler.module.patent.service.IPatentService;
import com.gmss.crawler.module.person.service.IPersonInfoService;
import com.gmss.crawler.module.title.domain.PersonTitle;
import com.gmss.crawler.module.title.service.IPersonTitleService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 专利表 前端控制器
 * </p>
 *
 * @author Auto-generator
 * @since 2021-10-21
 */
@RestController
@RequestMapping("/patent")
public class PatentController extends Base {

    @Resource
    private IPatentService iPatentService;
    @Resource
    private IPersonInfoService iPersonInfoService;
    @Resource
    private IPersonTitleService iPersonTitleService;


    /**
     * 通过id查询
     */
    @GetMapping("/getById/{id}")
    public String getById(@PathVariable(value = "id") Integer id) {
        return respJson(CommonEnum.SUCCESS, iPatentService.getById(id));
    }

    /**
     * 新增
     */
    @PostMapping("/save")
    public String save(@RequestBody Patent patent) {
        iPatentService.save(patent);
        return respJson(CommonEnum.SUCCESS);
    }

    /**
     * 通过id删除
     */
    @DeleteMapping("/deleteById/{id}")
    public String delete(@PathVariable(value = "id") String ids) {
        String[] idsStrs = ids.split(",");
        for (String id : idsStrs) {
            iPatentService.removeById(Integer.parseInt(id));
        }
        return respJson(CommonEnum.SUCCESS);
    }

    /**
     * 修改
     */
    @PutMapping("/update")
    public String updateById(@RequestBody Patent patent) {
        iPatentService.updateById(patent);
        return respJson(CommonEnum.SUCCESS);
    }

    /**
     * 查询列表
     */
    @PostMapping("/list")
    public String list(@RequestBody PatentReqVo patent) {
        final LambdaQueryWrapper<Patent> lambda = new QueryWrapper<Patent>().lambda();
        this.buildCondition(lambda, patent);
        return respJson(CommonEnum.SUCCESS, iPatentService.list(lambda));
    }

    /**
     * 分页查询
     */
    @PostMapping("/page")
    public String page(@RequestBody PatentReqVo pageParam) {
        final LambdaQueryWrapper<Patent> lambda = new QueryWrapper<Patent>().lambda();
        this.buildCondition(lambda, pageParam);
        final IPage<Patent> page = iPatentService.page(new Page<>(Constants.PAGE_NO, Constants.PAGE_SIZE), lambda);
        return respJson(CommonEnum.SUCCESS, page);
    }

    /**
     * 导出专利信息
     *
     * @param str
     * @return
     * @throws Exception
     */
    @PostMapping("/exportPatent")
    public String exportPatent(@RequestBody String str) throws Exception {
        if (StringUtils.isBlank(str))
            return respJson(CommonEnum.PARAM_NULL_ERROR);

        Map<String, Object> map = JSON.parseObject(str);
        if (MapUtils.isEmpty(map))
            return respJson(CommonEnum.PARAM_NULL_ERROR);

        if (!map.containsKey("filePath") || StringUtils.isBlank(map.get("filePath").toString())) {
            return respJson(CommonEnum.PARAM_ERROR, "导出excel的路径不能为空！");
        }

        if (!map.containsKey("fileName") || StringUtils.isBlank(map.get("fileName").toString())) {
            return respJson(CommonEnum.PARAM_ERROR, "导出excel的文件名称不能为空！");
        } else {
            String fileName = map.get("fileName").toString();
            String fileNamesuffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            if (!StringUtils.equalsAny(fileNamesuffix, "xlsx", "xls")) {
                return respJson(CommonEnum.PARAM_ERROR, "导出excel的文件名称后缀不正确，后缀应该为xlsx或xls ");
            }
        }

        if (!map.containsKey("exportType") || StringUtils.isBlank(map.get("exportType").toString())) {
            return respJson(CommonEnum.PARAM_ERROR, "导出类型(exportType)不能为空！0：院士信息，1：长江学者，2：杰出青年，3：百人计划");
        }

        String exportType = map.get("exportType").toString();
        List<Integer> list = new ArrayList<>();
        List<Patent> patentList = new ArrayList<>();
        List<PersonTitle> personTitleList = new ArrayList<>();
        LambdaQueryWrapper<PersonTitle> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<Long> personIds = new ArrayList<>();
        switch (exportType) {
            case "0":
                lambdaQueryWrapper = new LambdaQueryWrapper<>();
                list = iPersonInfoService.getAcademician();
                map.put("personTitles", list);
                patentList = iPatentService.queryExportExcelData(map);
                break;
            case "1":
                lambdaQueryWrapper = new LambdaQueryWrapper<>();
                list = new ArrayList<>();
                list.add(AcademicianEnum.CHANGJIANG_SCHOLAR_SPECIAL.getCode());
                list.add(AcademicianEnum.CHANGJIANG_SCHOLAR_LECTURE.getCode());
                list.add(AcademicianEnum.CHANGJIANG_SCHOLAR_YOUTH.getCode());
                map.put("personTitles", list);
                patentList = iPatentService.queryExportExcelData(map);
                break;
            case "2":
                break;
            case "3":
                break;
            case "4":
                break;
            default:
                patentList = iPatentService.queryExportExcelData(map);
                break;
        }
        boolean bool = iPatentService.writeExcel(map.get("filePath").toString(), map.get("fileName").toString(), patentList);
        if (bool) {
            return respJson(CommonEnum.SUCCESS, "导出excel路径:" + map.get("filePath").toString() + File.separator + map.get("fileName").toString());
        } else {
            return respJson(CommonEnum.FAILURE);
        }
    }


    /**
     * 构造查询条件
     *
     * @param lambda
     * @param param
     */
    private void buildCondition(LambdaQueryWrapper<Patent> lambda, PatentReqVo param) {
        if (param.getId() != null) {
            lambda.eq(Patent::getId, param.getId());
        }
        if (param.getPersonId() != null) {
            lambda.eq(Patent::getPersonId, param.getPersonId());
        }
        if (param.getLanguageStandard() != null) {
            lambda.eq(Patent::getLanguageStandard, param.getLanguageStandard());
        }
        if (!StringUtils.isEmpty(param.getPatentName())) {
            lambda.eq(Patent::getPatentName, param.getPatentName());
        }
        if (!StringUtils.isEmpty(param.getPatentType())) {
            lambda.eq(Patent::getPatentType, param.getPatentType());
        }
        if (!StringUtils.isEmpty(param.getInstituteStandard())) {
            lambda.eq(Patent::getInstituteStandard, param.getInstituteStandard());
        }
        if (!StringUtils.isEmpty(param.getApplyNum())) {
            lambda.eq(Patent::getApplyNum, param.getApplyNum());
        }
        if (!StringUtils.isEmpty(param.getPatentNum())) {
            lambda.eq(Patent::getPatentNum, param.getPatentNum());
        }
        if (!StringUtils.isEmpty(param.getApplyDate())) {
            lambda.eq(Patent::getApplyDate, param.getApplyDate());
        }
        if (!StringUtils.isEmpty(param.getPublicAnnouncementNum())) {
            lambda.eq(Patent::getPublicAnnouncementNum, param.getPublicAnnouncementNum());
        }
        if (!StringUtils.isEmpty(param.getPublicAnnouncementDate())) {
            lambda.eq(Patent::getPublicAnnouncementDate, param.getPublicAnnouncementDate());
        }
        if (!StringUtils.isEmpty(param.getMainClassifyNum())) {
            lambda.eq(Patent::getMainClassifyNum, param.getMainClassifyNum());
        }
        if (!StringUtils.isEmpty(param.getClassifyNum())) {
            lambda.eq(Patent::getClassifyNum, param.getClassifyNum());
        }
        if (!StringUtils.isEmpty(param.getProposer())) {
            lambda.eq(Patent::getProposer, param.getProposer());
        }
        if (!StringUtils.isEmpty(param.getInventor())) {
            lambda.eq(Patent::getInventor, param.getInventor());
        }
        if (!StringUtils.isEmpty(param.getProposerAddress())) {
            lambda.eq(Patent::getProposerAddress, param.getProposerAddress());
        }
        if (!StringUtils.isEmpty(param.getPatentAgency())) {
            lambda.eq(Patent::getPatentAgency, param.getPatentAgency());
        }
        if (!StringUtils.isEmpty(param.getCity())) {
            lambda.eq(Patent::getCity, param.getCity());
        }
        if (!StringUtils.isEmpty(param.getAgent())) {
            lambda.eq(Patent::getAgent, param.getAgent());
        }
        if (!StringUtils.isEmpty(param.getPrincipalClaim())) {
            lambda.eq(Patent::getPrincipalClaim, param.getPrincipalClaim());
        }
        if (!StringUtils.isEmpty(param.getLegalStatus())) {
            lambda.eq(Patent::getLegalStatus, param.getLegalStatus());
        }
        if (!StringUtils.isEmpty(param.getDescribeData())) {
            lambda.eq(Patent::getDescribeData, param.getDescribeData());
        }
        if (!CollectionUtils.isEmpty(param.getCreateTimeList())) {
            lambda.ge(Patent::getCreateTime, param.getCreateTimeList().get(0));
            lambda.le(Patent::getCreateTime, param.getCreateTimeList().get(1));
        }
        if (!StringUtils.isEmpty(param.getCreateUser())) {
            lambda.eq(Patent::getCreateUser, param.getCreateUser());
        }
        if (!CollectionUtils.isEmpty(param.getUpdateTimeList())) {
            lambda.ge(Patent::getUpdateTime, param.getUpdateTimeList().get(0));
            lambda.le(Patent::getUpdateTime, param.getUpdateTimeList().get(1));
        }
        if (!StringUtils.isEmpty(param.getUpdateUser())) {
            lambda.eq(Patent::getUpdateUser, param.getUpdateUser());
        }
        lambda.orderBy(true, false, Patent::getId);
    }


    /**
     * 请求model
     */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    private static class PatentReqVo extends Patent {
        private List<String> createTimeList; // 创建时间起止
        private List<String> updateTimeList; // 修改时间起止
    }


}
